package com.sky.utils;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Data
@AllArgsConstructor
@Slf4j
public class MinioClientUtil {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;

    @SneakyThrows(Exception.class)
    public String upload(MultipartFile file, String objectName){
        InputStream inputStream = file.getInputStream();
        MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey,secretKey).build();
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .contentType(file.getContentType())
                        .stream(inputStream, inputStream.available(), -1)
                        .build());
        String url =
                minioClient.getPresignedObjectUrl(
                        GetPresignedObjectUrlArgs.builder()
                                .method(Method.GET)
                                .bucket(bucketName)
                                .object(objectName)
                                .expiry(60 * 60 * 24)
                                .build());
       return url;
    }
}
